package cn.szzsi._webpc;


import cn.szzsi._Config;
import cn.szzsi._web.BaseWebController;
import cn.szzsi.common.bean.CartItemCookie;
import cn.szzsi.common.bean.SystemConfig;
import cn.szzsi.common.bean.dto.Msg;
import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.kit.RegexUtils;
import cn.szzsi.common.kit.SystemConfigUtil;
import cn.szzsi.common.model.*;
import cn.szzsi.common.model.zshop.CompanyInfo;
import cn.szzsi.common.sms.SmsEmayUtil;
import cn.szzsi.core.kit.DesUtil;
import cn.szzsi.interceptor.CommonInterceptor;
import cn.szzsi.service.MailService;
import cn.szzsi.validator.MemberValidator;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.captcha.CaptchaRender;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheKit;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台类 - 用户(商户的会员)
 * Created by haotian on 2016/10/13.
 */
public class CustomerController extends BaseWebPcController<Member> {
    private Member member;
    private String uid;//商户id,也是用户的店铺id
    private String shopId;//店铺id
    private String path;//模板路径
    private Boolean isAgreeAgreement;//是否同意注册协议
    private String passwordRecoverKey;
    public static final String STATUS = "status";
    public static final String WARN = "warn";
    public static final String SUCCESS = "success";
    public static final String ERROR = "error";
    public static final String MESSAGE = "message";

    @Clear
    @Before(CommonInterceptor.class)
    public void wapLogin() {
        String shopId = getPara("shopId");
        getTemplatePath(shopId, "login");
    }

    @Clear
    @Before(CommonInterceptor.class)
    public void wapRegister() {
        String shopId = getPara("shopId");
        getTemplatePath(shopId, "register");
    }


    @Clear
    @Before(CommonInterceptor.class)
    public void login() {
        String username = getPara("member.username", "");
        String password = getPara("member.password", "");
        String captchaToken = getPara("j_captcha", "");
        shopId = getPara("shopId");

        SystemConfig systemConfig = getSystemConfig();
        Member loginMember = Member.dao.getCustomerByUsernameAndShopId(username, shopId);
        if (loginMember != null) {
            if (!Member.dao.verifyCustomer(username, password, shopId)) {
                if (systemConfig.getIsLoginFailureLock()) {
                    int loginFailureLockCount = getSystemConfig().getLoginFailureLockCount();
                    int loginFailureCount = loginMember.getInt("loginFailureCount") + 1;
                    if (loginFailureCount >= systemConfig.getLoginFailureLockCount()) {
                        loginMember.set("isAccountLocked", true);
                        loginMember.set("lockedDate", new Date());
                    }
                    loginMember.set("loginFailureCount", loginFailureCount);
                    loginMember.update();
                    if (getSystemConfig().getIsLoginFailureLock() && loginFailureLockCount - loginFailureCount <= 3) {
                        renderJson(Ret.fail("info", "若连续" + loginFailureLockCount + "次密码输入错误,账号将被锁定,还有" + (loginFailureLockCount - loginMember.getInt("loginFailureCount")) + " 次机会。"));
                        return;
                    } else {
                        renderJson(Ret.fail("info", "您的用户名或密码错误!"));
                        return;
                    }
                } else {
                    renderJson(Ret.fail("info", "您的用户名或密码错误!"));
                    return;
                }
            }
        } else {
            renderJson(Ret.fail("info", "用户名或密码错误!"));
            return;
        }

        loginMember.set("loginIp", getRequest().getRemoteAddr());
        loginMember.set("loginDate", new Date());
        loginMember.update();

        // 写入会员登录Session
        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, loginMember.getStr("id"));

        // 写入会员登录Cookie
        Cookie loginMemberUsernameCookie = null;
        Cookie loginTypeCookie = null;
        try {
            loginMemberUsernameCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(username.toLowerCase(), "UTF-8"));
            loginTypeCookie = new Cookie(Member.LOGIN_TYPE_COOKIE_NAME, "customer");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        loginMemberUsernameCookie.setPath(getRequest().getContextPath() + "/");
        loginTypeCookie.setPath(getRequest().getContextPath() + "/");
        getResponse().addCookie(loginMemberUsernameCookie);
        getResponse().addCookie(loginTypeCookie);

        // 合并购物车
        Cookie[] cookies = getRequest().getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
                    if (StringUtils.isNotEmpty(cookie.getValue())) {
                        JSONArray jsonArray = null;
                        try {
                            jsonArray = JSON.parseArray(URLDecoder.decode(cookie.getValue(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        List<CartItemCookie> cartItemCookieList = JSON.parseArray(jsonArray.toJSONString(), CartItemCookie.class);
                        for (CartItemCookie cartItemCookie : cartItemCookieList) {
                            Product product = Product.dao.findById(cartItemCookie.getI());
                            if (product != null) {
                                CartItem cartItem = new CartItem();
                                cartItem.set("member_id", loginMember.getStr("id"));
                                cartItem.set("product_id", product.getStr("id"));
                                cartItem.set("quantity", cartItemCookie.getQ());
                                cartItem.save(cartItem);
                            }
                        }
                    }
                }
            }
        }

        // 清空临时购物车Cookie
        Cookie cartItemCookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
        cartItemCookie.setPath(getRequest().getContextPath() + "/");
        cartItemCookie.setMaxAge(0);
        getResponse().addCookie(cartItemCookie);

        String redirectionUrl = getSessionAttr(Member.LOGIN_REDIRECTION_URL_SESSION_NAME);
        getRequest().getSession().removeAttribute(Member.LOGIN_REDIRECTION_URL_SESSION_NAME);
        path = CommonUtil.getPathByUidAndType(shopId, CommonUtil.isMobileDevice(getRequest()));//获取模板路径
        if (StringUtils.isEmpty(redirectionUrl)) {
            renderJson(Ret.ok().set("url", "/b/customerCenter?shopId=" + shopId + ""));
        } else {
            renderJson(Ret.ok().set("url", redirectionUrl));
        }
    }

    @Clear
    @Before(Tx.class)
    public void ajaxLogin() {
        String phone = getPara("phone");
        String password = getPara("password");
        if(StrKit.isBlank(phone)|| StrKit.isBlank(password)){
            renderJson(Msg.fail("手机号和密码不允许为空!！", ""));
            return;
        }
        Member loginMember = Member.dao.getByPhone(phone);
        if (loginMember != null) {
            if (!Member.dao.verifyCustomerByPassword(loginMember,password)) {
                renderJson(Msg.fail("您的用户名或密码错误！", ""));
                return;
            }
        } else {
            renderJson(Msg.fail("您的用户名或密码错误！", ""));
            return;
        }
        loginMember.set("loginIp", getRequest().getRemoteAddr());
        loginMember.set("loginDate", new Date());
        loginMember.update();

        // 写入会员登录Session
        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, loginMember.getStr("id"));

        // 写入会员登录Cookie和登录类型Cookie

        Cookie loginMemberUsernameCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, DesUtil.desEncode(_Config.p.get("mall_des_key"),loginMember.getPhone()));
        Cookie loginTypeCookie = new Cookie(Member.LOGIN_TYPE_COOKIE_NAME, "customer");

        loginMemberUsernameCookie.setPath(getRequest().getContextPath() + "/");
        loginTypeCookie.setPath(getRequest().getContextPath() + "/");
        getResponse().addCookie(loginMemberUsernameCookie);
        getResponse().addCookie(loginTypeCookie);

        // 合并购物车
        Cookie[] cookies = getRequest().getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
                    if (StringUtils.isNotEmpty(cookie.getValue())) {
                        JSONArray jsonArray = null;
                        try {
                            jsonArray = JSON.parseArray(URLDecoder.decode(cookie.getValue(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        List<CartItemCookie> cartItemCookieList = JSON.parseArray(jsonArray.toJSONString(), CartItemCookie.class);
                        for (CartItemCookie cartItemCookie : cartItemCookieList) {
                            Product product = Product.dao.findById(cartItemCookie.getI());
                            if (product != null) {
                                CartItem cartItem = new CartItem();
                                cartItem.set("member_id", loginMember.getStr("id"));
                                cartItem.set("product_id", product.getStr("id"));
                                cartItem.set("quantity", cartItemCookie.getQ());
                                cartItem.save(cartItem);
                            }
                        }
                    }
                }
            }
        }

        // 清空临时购物车Cookie
        Cookie cartItemCookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
        cartItemCookie.setPath(getRequest().getContextPath() + "/");
        cartItemCookie.setMaxAge(0);
        getResponse().addCookie(cartItemCookie);
        renderJson(Msg.SUCCESS);

    }

    //用户注册保存
    @Clear
    @Before(CommonInterceptor.class)
    public void register() {
        isAgreeAgreement = getParaToBoolean("isAgreeAgreement");
        member = getModel(Member.class);
        shopId = getPara("shopId");
        String rePassword = getPara("rePassword", "");

        if (Member.dao.isExistByCustomerUsername(member.getUsername(), shopId)) {
            renderHtml("<script>alert('用户名已存在!');history.go(-1);</script>");
            return;
        }
        if (!StringUtils.equalsIgnoreCase(member.getStr("password"), rePassword)) {
            renderHtml("<script>alert('两次密码输入不一致!!');history.go(-1);</script>");
            return;
        }

        member.set("username", member.getStr("username").toLowerCase());
        member.set("password", DigestUtils.md5Hex(member.getStr("password")));
        member.set("shopId", shopId);
        member.set("safeQuestion", null);
        member.set("safeAnswer", null);
        member.set("memberRankId", MemberRank.dao.getDefaultMemberRank(shopId).getStr("id"));
        member.set("point", 0);
        member.set("deposit", new BigDecimal("0"));
        member.set("isAccountEnabled", true);
        member.set("isAccountLocked", false);
        member.set("loginFailureCount", 0);
        member.set("passwordRecoverKey", null);
        member.set("lockedDate", null);
        member.set("loginDate", new Date());
        member.set("registerIp", getRequest().getRemoteAddr());
        member.set("loginIp", getRequest().getRemoteAddr());
        member.set("id", CommonUtil.getUUID());
        member.set("pid","0");
        member.set("pids","0");
        member.set("createDate", new Date());
        member.save();

        // 写入会员登录Session
        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getStr("id"));

        // 写入会员登录Cookie
        Cookie loginMemberCookie = null;
        Cookie loginTypeCookie = null;
        try {
            loginMemberCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(member.getStr("username").toLowerCase(), "UTF-8"));
            loginTypeCookie = new Cookie(Member.LOGIN_TYPE_COOKIE_NAME, "customer");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        loginMemberCookie.setPath(getRequest().getContextPath() + "/");
        loginTypeCookie.setPath(getRequest().getContextPath() + "/");
        getResponse().addCookie(loginMemberCookie);
        getResponse().addCookie(loginTypeCookie);

        // 合并购物车
        Cookie[] cookies = getRequest().getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
                    if (StringUtils.isNotEmpty(cookie.getValue())) {
                        JSONArray jsonArray = null;
                        try {
                            jsonArray = JSON.parseArray(URLDecoder.decode(cookie.getValue(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        List<CartItemCookie> cartItemCookieList = JSON.parseArray(jsonArray.toJSONString(), CartItemCookie.class);
                        for (CartItemCookie cartItemCookie : cartItemCookieList) {
                            Product product = Product.dao.findById(cartItemCookie.getI());
                            if (product != null) {
                                CartItem cartItem = new CartItem();
                                cartItem.set("member_id", member.getStr("id"));
                                cartItem.set("product_id", product.getStr("id"));
                                cartItem.set("quantity", cartItemCookie.getQ());
                                cartItem.save(cartItem);
                            }
                        }
                    }
                }
            }
        }
        // 清空临时购物车Cookie
        Cookie cartItemCookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
        cartItemCookie.setPath(getRequest().getContextPath() + "/");
        cartItemCookie.setMaxAge(0);
        getResponse().addCookie(cartItemCookie);
        if (!"0".equals(shopId)) {
            path = CommonUtil.getPathByUidAndType(shopId, CommonUtil.isMobileDevice(getRequest()));//获取模板路径
            setAttr("shopId", shopId);
            setAttr("path", path);
            redirect("/b/customerCenter?shopId=" + shopId + "");
        }

    }



    // Ajax验证码校验
    @Clear
    public void validateCaptcha() {
        String phone = getPara("phone");
        String inputRandomCode=getPara("inputRandomCode");
        phone=new String(Base64.decodeBase64(phone));
        inputRandomCode=new String(Base64.decodeBase64(inputRandomCode));
        boolean validateResult = CaptchaRender.validate(this, inputRandomCode);
        if (!validateResult) {
            renderJson(Ret.fail().set("info", "图形码错误"));
            return;
        } else {
            //同一个手机号限制一分钟之内只能发送一条
            Long lastTimeMillis = CacheKit.get("sms_last_time",phone);
            if(lastTimeMillis!=null){
                Long currentTimeMillis=System.currentTimeMillis();
                if((currentTimeMillis-lastTimeMillis)<60000){
                    renderJson(Ret.fail("info","您的操作过于频繁,请稍后再试!!"));
                    return;
                }

            }

            //Member member=Member.dao.getByPhone(phone);
            CompanyInfo companyInfo=CompanyInfo.dao.getByPhone(phone);
            if(companyInfo!=null){
                renderJson(Ret.fail("info","该手机号已经注册,请换个试试!"));
                return;
            }

            //【微米荟商城】您的验证码:686260 ，请勿泄露！感谢您的使用！
            String captcha = CommonUtil.getSixRandom();//六位纯数字验证码
            String message = "【微米荟商城】您的验证码:"+captcha+" ，请勿泄露！感谢您的使用！";
            boolean sendResult= SmsEmayUtil.sendToSms("0",phone,message,"yzm","wmh",captcha);
            if(sendResult){
                renderJson(Ret.ok("info","发送成功!"));
            }else{
                renderJson(Ret.fail("info","发送失败!"));
            }
        }
    }

    // Ajax会员注册保存
    @Clear
    @Before(Tx.class)
    public void ajaxRegister() {
        member = getModel(Member.class);
        String phone=member.getPhone();
        String password=member.getPassword();
        String phonecode=getPara("phonecode");
        if(StrKit.notBlank(phone)&&!RegexUtils.checkMobile(phone)){
            renderJson(Ret.fail("info","请输入正确手机号!"));
            return;
        }
        if(CacheKit.get("sms",phone)==null){
            renderJson(Ret.fail("info","手机验证码已过期,请重新获取!"));
            return;
        }
        if(!phonecode.equals(CacheKit.get("sms",phone).toString())){
            renderJson(Ret.fail("info","手机验证码错误!"));
            return;
        }

        if(StrKit.notBlank(password)&&!RegexUtils.checkNumLN(password)){
            renderJson(Ret.fail("info","密码只能输入数字、字母或者下划线!"));
            return;
        }

        member.set("username", phone);
        member.set("password", DigestUtils.md5Hex(member.getPassword()));
        //member.set("shopId", shopId);
        member.set("safeQuestion", null);
        member.set("safeAnswer", null);
        //member.set("memberRankId", MemberRank.dao.getDefaultMemberRank(shopId).getStr("id"));
        member.set("point", 0);
        member.set("deposit", new BigDecimal("0"));
        member.set("isAccountEnabled", true);
        member.set("isAccountLocked", false);
        member.set("loginFailureCount", 0);
        member.set("passwordRecoverKey", null);
        member.set("lockedDate", null);
        member.set("loginDate", new Date());
        member.set("registerIp", getRequest().getRemoteAddr());
        member.set("loginIp", getRequest().getRemoteAddr());
        member.set("id", CommonUtil.getUUID());
        member.set("createDate", new Date());
        member.save();

        // 写入会员登录Session
        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getId());

        // 写入会员登录Cookie
        Cookie loginMemberCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, DesUtil.desEncode(_Config.p.get("mall_des_key"),phone));
        Cookie loginTypeCookie = new Cookie(Member.LOGIN_TYPE_COOKIE_NAME, "customer");

        loginMemberCookie.setPath(getRequest().getContextPath() + "/");
        loginTypeCookie.setPath(getRequest().getContextPath() + "/");
        getResponse().addCookie(loginMemberCookie);
        getResponse().addCookie(loginTypeCookie);

        // 合并购物车
        Cookie[] cookies = getRequest().getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
                    if (StringUtils.isNotEmpty(cookie.getValue())) {
                        JSONArray jsonArray = null;
                        try {
                            jsonArray = JSON.parseArray(URLDecoder.decode(cookie.getValue(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        List<CartItemCookie> cartItemCookieList = JSON.parseArray(jsonArray.toJSONString(), CartItemCookie.class);
                        for (CartItemCookie cartItemCookie : cartItemCookieList) {
                            Product product = Product.dao.findById(cartItemCookie.getI());
                            if (product != null) {
                                CartItem cartItem = new CartItem();
                                cartItem.set("member_id", member.getStr("id"));
                                cartItem.set("product_id", product.getStr("id"));
                                cartItem.set("quantity", cartItemCookie.getQ());
                                cartItem.save(cartItem);
                            }
                        }
                    }
                }
            }
        }

        // 清空临时购物车Cookie
        Cookie cartItemCookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
        cartItemCookie.setPath(getRequest().getContextPath() + "/");
        cartItemCookie.setMaxAge(0);
        getResponse().addCookie(cartItemCookie);
        renderJson(Ret.ok().set("info","注册成功"));
    }

    // 密码找回
    public void passwordRecover() {
        uid = getPara("shopId");
        getTemplatePath(uid, "member_password_recover");

    }

    // 发送密码找回邮件
    @Before(MemberValidator.class)
    public void sendPasswordRecoverMail() {
        member = getModel(Member.class);
        Member persistent = Member.dao.getCustomerByUsername(member.getStr("username"));
        if (persistent == null || StringUtils.equalsIgnoreCase(persistent.getStr("email"), member.getStr("email")) == false) {
            ajaxJsonErrorMessage("用户名或E-mail输入错误！");
            return;
        }
        if (!MailService.service.isMailConfigComplete()) {
            ajaxJsonErrorMessage("系统邮件发送功能尚未配置，请联系管理员！");
            return;
        }
        if (StringUtils.isNotEmpty(persistent.getStr("safeQuestion")) && StringUtils.isNotEmpty(persistent.getStr("safeQuestion"))) {
            if (StringUtils.isEmpty(member.getStr("safeAnswer"))) {
                Map<String, String> jsonMap = new HashMap<String, String>();
                jsonMap.put("safeQuestion", persistent.getStr("safeQuestion"));
                jsonMap.put(STATUS, WARN);
                jsonMap.put(MESSAGE, "请填写密码保护问题答案！");
                renderJson(jsonMap);
                return;
            }
            if (StringUtils.equalsIgnoreCase(persistent.getStr("safeAnswer"), member.getStr("safeAnswer")) == false) {
                ajaxJsonErrorMessage("密码保护答案错误！");
                return;
            }
        }
        persistent.set("passwordRecoverKey", Member.dao.buildPasswordRecoverKey());
        persistent.set("modifyDate", new Date());
        persistent.update();

        if (MailService.service.sendPasswordRecoverMail(persistent)) {
            ajaxJsonSuccessMessage("系统已发送邮件到您的E-mail，请根据邮件提示操作！");
        } else {
            ajaxJsonErrorMessage("发送失败,请联系管理员！");
        }
    }

    // 密码修改
    public void passwordModify() {
        String id = getPara("id", "");
        passwordRecoverKey = getPara("passwordRecoverKey", "");

        Member persistent = Member.dao.findById(id);
        if (persistent == null || StringUtils.equalsIgnoreCase(persistent.getStr("passwordRecoverKey"), passwordRecoverKey) == false) {
            addActionError("对不起，此密码找回链接已失效！");
            return;
        }
        Date passwordRecoverKeyBuildDate = Member.dao.getPasswordRecoverKeyBuildDate(passwordRecoverKey);
        Date passwordRecoverKeyExpiredDate = DateUtils.addMinutes(passwordRecoverKeyBuildDate, Member.PASSWORD_RECOVER_KEY_PERIOD);
        Date now = new Date();
        if (now.after(passwordRecoverKeyExpiredDate)) {
            addActionError("对不起，此密码找回链接已过期！");
            return;
        }
        setAttr("member", persistent);
        render(CommonUtil.TEMPLATE_PATH + "/shop/member_password_modify.html");
    }

    // 密码更新
    @Before(MemberValidator.class)
    public void passwordUpdate() {
        member = getModel(Member.class);
        passwordRecoverKey = member.getStr("passwordRecoverKey");

        Member persistent = Member.dao.findById(member.getStr("id"));
        if (persistent == null || StringUtils.equalsIgnoreCase(persistent.getStr("passwordRecoverKey"), passwordRecoverKey) == false) {
            addActionError("对不起，此密码找回链接已失效！");
            return;
        }
        Date passwordRecoverKeyBuildDate = Member.dao.getPasswordRecoverKeyBuildDate(passwordRecoverKey);
        Date passwordRecoverKeyExpiredDate = DateUtils.addMinutes(passwordRecoverKeyBuildDate, Member.PASSWORD_RECOVER_KEY_PERIOD);
        Date now = new Date();
        if (now.after(passwordRecoverKeyExpiredDate)) {
            addActionError("对不起，此密码找回链接已过期！");
            return;
        }
        persistent.set("password", DigestUtils.md5Hex(member.getStr("password")));
        persistent.set("passwordRecoverKey", null);
        persistent.set("modifyDate", new Date());
        persistent.update();
        renderSuccessMessage("密码修改成功！", "/html/login.html");
    }

    // 获取注册协议内容
    public void agreement() {
        renderJson(Agreement.dao.getAll().getStr("content"));
    }

    // 检查用户名是否存在
    public void checkUsername() {
        String username = getPara("member.username", "");
        shopId = getPara("shopId");
        if (Member.dao.isExistByCustomerUsername(username, shopId)) {
            System.out.println("**************用户名已存在");
            renderText("false");
        } else {
            System.out.println("**************用户名不存在");
            renderText("true");
        }
    }

    public void addActionError(String error) {
        setAttr("errorMessages", error);
        redirect("/common/error.html");
        render(CommonUtil.TEMPLATE_PATH + "/common/error.html");
    }

    @Clear
    public void renderErrorMessage(String message) {
        setAttr("errorMessages", message);
        setAttr("systemConfig", SystemConfigUtil.getSystemConfig());
        setAttr("base", getRequest().getContextPath());
        render(CommonUtil.TEMPLATE_PATH + "/admin/error.html");
    }

    // 获取系统配置信息
    public SystemConfig getSystemConfig() {
        return SystemConfigUtil.getSystemConfig();
    }

    // 输出JSON错误消息，返回null
    public void ajaxJsonErrorMessage(String message) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, ERROR);
        jsonMap.put(MESSAGE, message);
        renderJson(jsonMap);
    }

    // 输出JSON成功消息，返回null
    public void ajaxJsonSuccessMessage(String message) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, SUCCESS);
        jsonMap.put(MESSAGE, message);
        renderJson(jsonMap);
    }

    public void renderSuccessMessage(String message, String url) {
        setAttr(MESSAGE, message);
        setAttr("redirectionUrl", url);
        render(CommonUtil.TEMPLATE_PATH + "/shop/success.html");
    }
}
